from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from smartid.settings import BASE_DIR
from . import models
from django.http import HttpResponse
from django.conf import settings
import os
from .models import Blog, Tools, Images


# Create your views here.
from .utils.aliapi import test_segment


def upload(requests):
    if requests.method == 'POST':
        img = requests.FILES.get('picture')

        media_root = settings.MEDIA_ROOT  # media
        allow_upload = settings.ALLOW_UPLOAD  # ALLOW_UPLOAD
        path = media_root + '/upload'
        if not os.path.exists(path):  # 判断路径是否存在
            os.makedirs(path)  # 创建此路径
        if img.name.split('.')[-1] not in allow_upload:
            return HttpResponse('fail')

        url = path + '/' + img.name

        from photos.utils.aliapi import test_segment
        data = test_segment(requests)
        print(data)

        # 将图片写入数据库
        # models.Images.objects.create(pic=data)
        print(url)

        return render(requests, 'show.html', {'img': url, 'data': data})

    else:
        return render(requests, 'upload.html')


# 上传图片
def index(requests):
    return render(requests, 'upload.html')


# def download(requests):
#     return render(requests,'show.html')

#工具列表
def tool(requests):
    tools = Tools.objects.all()
    return render(requests, 'tools.html', {'tools': tools})

#博客展示
def blog(requests):
    blogs = Blog.objects.all()
    return render(requests, 'blog.html', {'blogs': blogs})

#处理图片汇总显示
def detail(requests):
    images = Images.objects.all()
    return render(requests, 'detail.html', {'images': images})